package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.BindingAdapter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.databinding.VehicleActivityProblemBinding;
import com.qbw.app.model.Problem;
import com.qbw.app.model.ProblemStatus;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.app.module.vehicle.adapter.VehicleAdapter;
import com.qbw.app.module.vehicle.holder.VehicleProblemCategoryHolder;
import com.qbw.customview.RefreshLoadMoreLayout;

import static com.qbw.app.module.vehicle.adapter.VehicleViewType.VT_PROBLEM_CATEGORY_GROUP;
import static com.qbw.app.module.vehicle.adapter.VehicleViewType.VT_PROBLEM_ITEM;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_PROGLEM_LIST;

/**
 * 车辆故障
 *
 * @author QBW
 * @date 2019-08-24
 */
public class VehicleProblemActivity extends CommonActivity<VehicleActivityProblemBinding> implements VehicleProblemCategoryHolder.Listener, HttpTask.CallBack, RefreshLoadMoreLayout.CallBack {

    //private static final int STATUS_NO_DATA = 1;

    private VehicleAdapter mVehicleAdapter;
    //private String mVehicleCode;
    private ProblemStatus mProblemStatus;
    private Problem.Data mProglemData;

    //private ObservableInt mObservableStatus = new ObservableInt();

    public static void startActivity(Context context, ProblemStatus status) {
        Intent intent = new Intent(context, VehicleProblemActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_FAULT, status);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_problem;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mProblemStatus = (ProblemStatus) args.getSerializable(Constant.KEY_FAULT);
        mBinding.title.setSubTitle(mProblemStatus.getVehicle().getVehicleNick());
        mBinding.title.setSubTitleVisible(true);
        mBinding.title.setListener(this);
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rcv.addItemDecoration(new InnerDecoration());
        mVehicleAdapter = new VehicleAdapter(this, this);
        mBinding.rcv.setAdapter(mVehicleAdapter);
        mBinding.rll.init(new RefreshLoadMoreLayout.Config(this).canLoadMore(false));
        //mBinding.setStatus(mObservableStatus);
        mBinding.setStatus(mProblemStatus);
        mBinding.executePendingBindings();
        /*if (ProblemStatus.NORMAL.equals(mProblemStatus) && mProblemStatus.getFaultCount() <= 0) {
            mProblemStatus.setState(ProblemStatus.NO_DATA);
        }*/
        //if (!ProblemStatus.NO_DATA.equals(mProblemStatus.getState())) {
        mBinding.rll.startAutoRefresh();
        //}
    }

    @BindingAdapter({"problemNoDataImage", "faultCount"})
    public static void setProblemNoDataImage(ImageView iv, String status, int faultCount) {
        if (ProblemStatus.NO_DATA.equals(status)) {
            iv.setImageResource(R.drawable.no_data);
        } else {
            if (faultCount <= 0) {
                iv.setImageResource(R.drawable.no_warning);
            }
        }
        //iv.setImageResource(R.drawable.no_data);
        //iv.setImageResource(R.drawable.no_guzhang);
    }

    @BindingAdapter({"problemNoDataTitle", "faultCount"})
    public static void setProblemNoDataTitle(TextView tv, String status, int faultCount) {
        if (ProblemStatus.NO_DATA.equals(status)) {
            tv.setText(R.string.no_data);
        } else {
            if (faultCount <= 0) {
                tv.setText(R.string.no_problem);
            }
        }
        //tv.setText(R.string.no_data);
        //tv.setText(R.string.no_problem);
    }

    @BindingAdapter({"faultErrorShow", "faultCount"})
    public static void setErrorShow(View v, String status, int faultCount) {
        v.setVisibility(ProblemStatus.NO_DATA.equals(status) || faultCount <= 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onRefresh() {
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getProblemList(mProblemStatus.getVehicle().getVehicleCode(), this)
                       .execute();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        String method = httpTask.getMethod();
        if (method.equals(METHOD_PROGLEM_LIST)) {
            Problem.Response response = (Problem.Response) entity;
            Problem.Data data = response.getData();
            mProglemData = data;
            mVehicleAdapter.clear();
            //if (data.realFaultListSize() > 0 || data.historyFaultListSize() > 0) {
            //mProblemStatus.setState(ProblemStatus.NORMAL);
            //mProblemStatus.setFaultCount(data.realFaultListSize() + data.historyFaultListSize());
            mVehicleAdapter.addGroup(new VehicleProblemCategoryHolder.Data(ResUtil.getString(R.string.problem_existed)));
            mVehicleAdapter.addGroupChild(0, data.getRealFaultList());
            mVehicleAdapter.addGroup(new VehicleProblemCategoryHolder.Data(ResUtil.getString(R.string.problem_history)));
            mVehicleAdapter.addGroupChild(1, data.getHistoryFaultRowList());
            //} else {
            //mProblemStatus.setState(ProblemStatus.NO_DATA);
            //}

            //mBinding.tvUpdateTime.setVisibility(ProblemStatus.NO_DATA.equals(mProblemStatus.getState()) ? View.GONE : View.VISIBLE);
            VehicleDataBindingAdapter.setVehicleLastUpdateTime(mBinding.tvUpdateTime,
                                                               data.getLastUpdateTime());
            mBinding.rll.stopRefresh();
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        String method = httpTask.getMethod();
        if (method.equals(METHOD_PROGLEM_LIST)) {
            mBinding.rll.stopRefresh();
        }
    }

    @Override
    public void onClickVehicleProblemCategory(VehicleProblemCategoryHolder.Data data) {
        String category = data.getCategory();
        if (category.equals(ResUtil.getString(R.string.problem_existed))) {
            int gp = getProglemCategoryGroupPosition(category);
            if (gp != -1) {
                if (data.isOpened()) {
                    mVehicleAdapter.addGroupChild(gp, mProglemData.getRealFaultList());
                } else {
                    mVehicleAdapter.clearGroupChild(gp);
                }
            }

        } else if (category.equals(ResUtil.getString(R.string.problem_history))) {
            int gp = getProglemCategoryGroupPosition(category);
            if (gp != -1) {
                if (data.isOpened()) {
                    mVehicleAdapter.addGroupChild(gp, mProglemData.getHistoryFaultRowList());
                } else {
                    mVehicleAdapter.clearGroupChild(gp);
                }
            }
        }
    }

    private int getProglemCategoryGroupPosition(String category) {
        int gc = mVehicleAdapter.getGroupCount();
        for (int i = 0; i < gc; i++) {
            Object o = mVehicleAdapter.getGroup(i);
            if (o instanceof VehicleProblemCategoryHolder.Data) {
                if (((VehicleProblemCategoryHolder.Data) o).getCategory().equals(category)) {
                    return i;
                }
            }
        }
        return -1;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(Constant.KEY_FAULT, mProblemStatus);
    }

    private static class InnerDecoration extends RecyclerView.ItemDecoration {
        private Paint mPaint;
        private int mSpace1;

        public InnerDecoration() {
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setColor(ResUtil.getColor(R.color.item_line));
            mSpace1 = ScreenUtil.dp2px(XApplication.getInstance(), 16);
        }

        @Override
        public void onDrawOver(@NonNull Canvas c,
                               @NonNull RecyclerView parent,
                               @NonNull RecyclerView.State state) {
            super.onDrawOver(c, parent, state);
            int cc = parent.getChildCount();
            View view;
            int ap;
            int vt;
            RecyclerView.Adapter adapter = parent.getAdapter();
            for (int i = 0; i < cc; i++) {
                view = parent.getChildAt(i);
                ap = parent.getChildAdapterPosition(view);
                if (ap == RecyclerView.NO_POSITION) {
                    continue;
                }
                vt = adapter.getItemViewType(ap);
                if (vt == VT_PROBLEM_CATEGORY_GROUP) {
                    c.drawRect(view.getLeft(),
                               view.getBottom() - 1,
                               view.getRight(),
                               view.getBottom(),
                               mPaint);
                } else if (vt == VT_PROBLEM_ITEM) {
                    c.drawRect(view.getLeft() + mSpace1,
                               view.getBottom() - 1,
                               view.getRight() - mSpace1,
                               view.getBottom(),
                               mPaint);
                }
            }
        }
    }
}
